package com.zscat.platform.bak;

import com.zscat.common.utils.ThreadPoolUtils;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: shenzhuan
 * @Date: 2018/12/19 10:06
 * @Description:
 */
public class TestRunner {
    /**
     * 小程序任务推送
     *
     * @return
     */
    /*
    public ResultInfoObject pushMsg(Integer id, String userName) {
        ResultInfoObject resultInfo = new ResultInfoObject();
        //针对于售后服务重复数据进行redis加锁，处理并发问题
        String key = "health_cache_push_" + id;
        if(JedisUtil.keyExists(key)) {
            resultInfo.setCode(CommonConstant.PARAM_ERROR_CODE);
            resultInfo.setMsg("操作过于频繁，请稍后再试！");
            return resultInfo;
        }

        JedisUtil.setex(key, 300, "1");

        log.info("[pushMsg] add redis lock key : {}", key);

        HealthPushTask healthPushTask = healthPushTaskDao.selectByPrimaryKey(id);

        if (healthPushTask.getStatus()==2){ //已发送
            log.info("此任务已发送id="+healthPushTask.getId());
            resultInfo.setCode(CommonConstant.PARAM_ERROR_CODE);
            resultInfo.setObject("此任务已发送id="+healthPushTask.getId());
            return resultInfo ;
        }
        healthPushTask.setStatus(2);
        healthPushTask.setUpdateTime(new Date());
        healthPushTaskDao.updateByPrimaryKeySelective(healthPushTask);
        List<HealthPushTaskUser> healthPushTaskUserList = healthPushTaskUserDao.selectListByTaskId(id);
        if (healthPushTaskUserList== null|| healthPushTaskUserList.size()<1){
            log.info("还没有上传用户ID");
            resultInfo.setCode(CommonConstant.PARAM_ERROR_CODE);
            resultInfo.setObject("还没有上传用户ID");
            return resultInfo ;
        }
        List<HealthPushUserFromIdRecord> healthPushUserFromIdRecordList = healthPushUserFromIdRecordDao.selectAvialFormId();
        if (healthPushUserFromIdRecordList== null|| healthPushUserFromIdRecordList.size()<1){
            log.info("没有formid");
            resultInfo.setCode(CommonConstant.PARAM_ERROR_CODE);
            resultInfo.setObject("没有formid");
            return resultInfo ;
        }

        Map<String, HealthPushUserFromIdRecord> formIdMap = new HashMap();
        AtomicInteger successCount = new AtomicInteger(0);
        for (HealthPushUserFromIdRecord s : healthPushUserFromIdRecordList) {
            formIdMap.put(s.getUserId() + "", s);
        }
        int totalCount = healthPushTaskUserList.size();

        //多线程分发
        final int size = 100;
        int threadCount = (totalCount + size - 1) / size;
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for(int i=0;i<threadCount;i++) {
            final int beginIndex = i * size;
            final int endIndex = (threadCount - i) ==1 ? totalCount : (beginIndex + size);
            ThreadPoolUtils.addProcess(new Runnable() {
                @Override
                public void run() {
                    List<HealthPushTaskUser> subList = new ArrayList<>(healthPushTaskUserList.subList(beginIndex,endIndex));
                    log.info("小程序推送子list范围: {}-{}",beginIndex , endIndex);

                    for (HealthPushTaskUser healthPushTaskUser : subList) {
                        HealthUser healthUser = healthUserDao.selectByPrimaryKey(Long.valueOf(healthPushTaskUser.getUserId()));
                        if (healthUser != null && healthUser.getOpenid() != null) {
                            HealthPushUserFromIdRecord healthPushUserFromIdRecord =formIdMap.get(healthUser.getUserId() + "");

                            try {
                                if (healthPushUserFromIdRecord== null){
                                    log.info(healthUser.getUserId()+"没有formid");
                                    healthPushTaskUser.setUpdateTime(new Date());
                                    healthPushTaskUser.setStatus(3);
                                    healthPushTaskUser.setNote("没有formid");
                                    healthPushTaskUserDao.updateByPrimaryKeySelective(healthPushTaskUser);
                                    continue;
                                }
                                String page ="pages/goods/detail/detail";
                                String  accessToken = wechatApiService.getAccessToken("health_applet");
                                String templateId = healthPushTask.getTemplateId();
                                Map<String, TemplateData> param = new HashMap<String, TemplateData>();
                                param.put("keyword1", new TemplateData(healthPushTask.getTaskTopic(), "#EE0000"));
                                param.put("keyword2", new TemplateData(healthPushTask.getTaskCaption(), "#EE0000"));
                                param.put("keyword3", new TemplateData(healthPushTask.getGoodsName(), "#EE0000"));
                                param.put("keyword4", new TemplateData( Validator.doubleTrans(Validator.rountTwo(healthPushTask.getPrice().doubleValue()))+"海贝", "#EE0000"));
                                param.put("keyword5", new TemplateData( healthPushTask.getTaskTips(), "#EE0000"));

                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(JSON.toJSONString(param));
//			        //调用发送微信消息给用户的接口    ********这里写自己在微信公众平台拿到的模板ID
                                JSONObject resultJson = WX_TemplateMsgUtil.sendWechatMsgToUser(healthUser.getOpenid(), templateId, page + "?backToHome=1&&goodsId=" + healthPushTask.getGoodsId(),
                                        healthPushUserFromIdRecord.getFormId(), jsonObject, accessToken);
                                String errmsg = "error";
                                if (resultJson!=null){
                                    errmsg = (String) resultJson.get("errmsg");
                                }
                                if ("ok".equals(errmsg)){
                                    healthPushTaskUser.setStatus(1);
                                    successCount.incrementAndGet();
                                }else {
                                    healthPushTaskUser.setStatus(3);
                                    // errorCount++;
                                }
                                healthPushUserFromIdRecord.setStatus(2);
                                healthPushUserFromIdRecord.setUpdateTime(new Date());
                                healthPushUserFromIdRecordDao.updateByPrimaryKeySelective(healthPushUserFromIdRecord);
                                healthPushTaskUser.setUpdateTime(new Date());
                                healthPushTaskUser.setNote(errmsg);
                                healthPushTaskUser.setFormId(healthPushUserFromIdRecord.getFormId());
                                healthPushTaskUserDao.updateByPrimaryKeySelective(healthPushTaskUser);
                            } catch (Exception e) {
                                resultInfo.setMsg("发送失败");
                                resultInfo.setCode(CommonConstant.PARAM_ERROR_CODE);
                                log.error("APPPUSH:"+e.getMessage());
                            }
                        } else {
                            healthPushTaskUser.setUpdateTime(new Date());
                            healthPushTaskUser.setStatus(3);
                            healthPushTaskUser.setNote("用户不存在或者openid不存在");
                            healthPushTaskUserDao.updateByPrimaryKeySelective(healthPushTaskUser);
                            log.info("APPPUSH:用户不存在或者openid不存在=" + healthPushTaskUser.getUserId());
                        }
                    }

                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("小程序推送线程中断，错误：{}", e.getMessage());
        }

        String obj = "总发送数量="+totalCount+",发送成功数量="+successCount.get()+",发送失败数量="+(totalCount-successCount.get());
        log.info(obj);
        resultInfo.setObject(obj);
        resultInfo.setCode(CommonConstant.RET_SUCCESS);
        return resultInfo;
    }
    */
    public static void main1(String[] args) {
        Future<Integer> countFuture = ThreadPoolUtils.addTask(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 1;
            }
        });

        try {

            Integer count = countFuture.get(3, TimeUnit.SECONDS);

        } catch (Exception e) {

        }
    }
}
